<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Shop\Controller;

use Admin\Data\Common;
use Admin\Data\Config;
use Admin\Service\Common\PhoneMessage;
use Doctrine\ORM\EntityManager;
use Laminas\Config\Factory;
use Laminas\Filter\StaticFilter;
use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\Mvc\I18n\Translator;
use PHPQRCode\QRcode;

class IndexController extends AbstractActionController
{
    private $translator;
    private $entityManager;

    public function __construct(
        Translator      $translator,
        EntityManager   $entityManager
    )
    {
        $this->translator   = $translator;
        $this->entityManager= $entityManager;
    }

    /**
     * 首页
     * @return array|\Laminas\Http\Response|\Laminas\View\Model\ViewModel
     */
    public function indexAction()
    {
        //当前的页面，用来区分首页在layout中使用
        $this->layout()->setVariable('shopCurrentPage', 'index');

        $indexPartial = $this->shopPlugin()->shopPartial('index');

        return ['indexPartial' => $indexPartial];
    }

    /**
     * 切换货币
     */
    public function changeCurrencyAction()
    {
        $currencyCode = StaticFilter::execute($this->request->getQuery('code'), 'StringToUpper');
        $currencyInfo = Common::configValue($currencyCode, 'currency');
        if($currencyInfo && $currencyInfo['state'] == 1) {
            $this->shopPlugin()->setDbshopSessionData('currencyCode', $currencyInfo['code']);
        }
        return $this->shopPlugin()->toReferer();
    }

    /**
     * 手机验证码发送
     * @return mixed
     */
    public function sendPhoneCaptchaAction()
    {
        $areaCode   = $this->params()->fromPost('areaCode', '');
        $phoneNumber= $this->params()->fromPost('phoneNumber', '');

        if (empty($phoneNumber)) return $this->response->setContent($this->translator->translate('请填写手机号码!'));
        if (!Common::checkPhoneNumber($phoneNumber, $areaCode)) return $this->response->setContent($this->translator->translate('手机号码不正确!'));

        $expiredTime = (int) $this->shopPlugin()->getDbshopSessionData('expiredTime');
        if ($expiredTime > 0 && $expiredTime > time()) return $this->response->setContent($this->translator->translate('获取时间未到，不可重复获取验证码!'));

        $number = '1234567890';
        for($i=0; $i<10; $i++) {
            $num[$i] = $number[$i];
        }
        mt_srand((double) microtime() * 10000);
        shuffle($num);
        $phoneCaptcha = substr(implode('',$num), 2, 6);

        $this->shopPlugin()->setDbshopSessionData('phoneCaptcha', $phoneCaptcha);
        $this->shopPlugin()->setDbshopSessionData('phoneNumber', $phoneNumber);
        $this->shopPlugin()->setDbshopSessionData('expiredTime', time() + Config::PHONE_CAPTCHA_EXPIRED_SECOND);

        $message = '';
        try {
            PhoneMessage::sendSms(['phoneAreaCode' => $areaCode, 'phone' => $phoneNumber, 'contentArray' => ['phoneCaptcha' => $phoneCaptcha], 'templateCode' => 'captcha']);
        } catch (\Exception $e) {
            $message = $this->translator->translate('验证码发送错误!');
        }

        return $this->response->setContent($message);
    }

    /**
     * 通过url调用二维码
     * @return mixed
     */
    public function shopQrCodeFileAction()
    {
        if(!$this->shopPlugin()->validatorQueryCsrf()) return $this->response->setContent('非法访问!');
        return $this->response->setContent(QRcode::png(urldecode($this->params()->fromQuery('data')), false, 0, 8, 1));
    }

    public function outputUpdateKeyAction()
    {
        $updateKey      = '';
        $actionName     = StaticFilter::execute($this->params()->fromQuery('actionName'), 'HtmlEntities');
        $updateKeyArray = Factory::fromFile(Config::PACKAGE_UPDATE_KEY_FILE);
        if (isset($updateKeyArray[$actionName]) && !empty($updateKeyArray[$actionName])) $updateKey = $updateKeyArray[$actionName];

        return $this->response->setContent($updateKey);
    }
}